{% extends "base.html" %}

{% block title %}任务中心 - 梦幻西游数字资产管理系统{% endblock %}

{% block mobile_title %}任务中心{% endblock %}

{% block content %}
<script>document.body.setAttribute('data-page', 'tasks');</script>
<div class="container-fluid tasks-page">
    <div class="row mb-4">
        <div class="col-md-6">
            <h2 class="page-title">📋 任务中心</h2>
        </div>
        <div class="col-md-6 text-md-end">
            <div class="btn-group-mobile">
                <button class="btn btn-danger" onclick="batchDelete()">
                    <i class="bi bi-trash me-1"></i>删除当天
                </button>
                <button class="btn btn-warning" onclick="batchComplete()">
                    <i class="bi bi-check-all me-1"></i>批量完成
                </button>
                <button class="btn btn-info" onclick="showAddTaskModal()">
                    <i class="bi bi-plus-circle me-1"></i>手工录入
                </button>
                <button class="btn btn-success" onclick="generateTodayTasks()">
                    <i class="bi bi-calendar-plus me-1"></i>生成今日
                </button>
            </div>
        </div>
    </div>
    
    <!-- 日期选择和筛选 -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row align-items-center mb-3">
                <div class="col-md-6">
                    <div class="input-group">
                        <button class="btn btn-outline-secondary" onclick="changeDate(-1)">
                            <i class="bi bi-chevron-left"></i>
                        </button>
                        <input type="date" class="form-control" id="taskDate" onchange="loadTasks()">
                        <button class="btn btn-outline-secondary" onclick="changeDate(1)">
                            <i class="bi bi-chevron-right"></i>
                        </button>
                        <button class="btn btn-primary" onclick="setToday()">今天</button>
                    </div>
                </div>
                <div class="col-md-6 text-md-end mt-3 mt-md-0">
                    <div class="d-flex justify-content-md-end gap-3">
                        <div>
                            <h4 class="mb-0" id="completionRate">0%</h4>
                            <small class="text-muted">完成率</small>
                        </div>
                        <div>
                            <h4 class="mb-0" id="taskStats">0/0</h4>
                            <small class="text-muted">已完成/总数</small>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 高级查询 -->
            <div class="row g-3">
                <div class="col-md-2">
                    <label class="form-label small">顺序（最小）</label>
                    <input type="number" class="form-control" id="searchOrderMin" placeholder="最小值">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">顺序（最大）</label>
                    <input type="number" class="form-control" id="searchOrderMax" placeholder="最大值">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">角色名</label>
                    <input type="text" class="form-control" id="searchRole" placeholder="搜索角色名...">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">账号名</label>
                    <input type="text" class="form-control" id="searchAccount" placeholder="搜索账号名...">
                </div>
                <div class="col-md-2">
                    <label class="form-label small">任务类型</label>
                    <select class="form-select" id="filterTaskType">
                        <option value="">全部任务类型</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label small">完成状态</label>
                    <select class="form-select" id="filterStatus">
                        <option value="">全部状态</option>
                        <option value="completed">已完成</option>
                        <option value="pending">未完成</option>
                    </select>
                </div>
            </div>
            <div class="row g-3 mt-2">
                <div class="col-md-4">
                    <label class="form-label small">任务备注</label>
                    <input type="text" class="form-control" id="searchNotes" placeholder="搜索备注...">
                </div>
                <div class="col-md-8 text-end align-self-end">
                    <button class="btn btn-outline-secondary me-2" onclick="resetTaskSearch()">
                        <i class="bi bi-x-circle me-1"></i>重置
                    </button>
                    <button class="btn btn-primary" onclick="loadTasks()">
                        <i class="bi bi-search me-1"></i>查询
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 桌面端表格视图 -->
    <div class="card table-responsive">
        <div class="card-body">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll" onchange="toggleSelectAll()"></th>
                        <th onclick="sortTable('order')" style="cursor:pointer;">
                            顺序 <i class="bi bi-arrow-down-up"></i>
                        </th>
                        <th onclick="sortTable('role_name')" style="cursor:pointer;">
                            角色名 <i class="bi bi-arrow-down-up"></i>
                        </th>
                        <th>账号</th>
                        <th onclick="sortTable('task_type')" style="cursor:pointer;">
                            任务类型 <i class="bi bi-arrow-down-up"></i>
                        </th>
                        <th>目标次数</th>
                        <th>已完成次数</th>
                        <th onclick="sortTable('is_completed')" style="cursor:pointer;">
                            完成状态 <i class="bi bi-arrow-down-up"></i>
                        </th>
                        <th>完成时间</th>
                        <th>备注</th>
                        <th style="width: 150px;">操作</th>
                    </tr>
                </thead>
                <tbody id="taskTableBody">
                    <tr>
                        <td colspan="11" class="text-center">
                            <div class="spinner-border text-primary my-3" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- 移动端卡片视图 -->
    <div class="table-mobile-cards" id="taskMobileCards">
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
        </div>
    </div>
</div>

<!-- 手工录入任务模态框 -->
<div class="modal fade" id="addTaskModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">➕ 手工录入任务</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addTaskForm">
                    <div class="mb-3">
                        <label class="form-label">任务日期 *</label>
                        <input type="date" class="form-control" id="taskInputDate" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">选择角色 *</label>
                        <select class="form-select" id="taskRoleId" required onchange="updateAccountId()">
                            <option value="">请选择角色</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">任务类型 *</label>
                        <select class="form-select" id="taskType" required>
                            <option value="">请选择</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">目标次数</label>
                        <input type="number" class="form-control" id="taskTargetCount" value="1" min="1">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">任务备注</label>
                        <textarea class="form-control" id="taskNotes" rows="2"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveTask()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑任务模态框 -->
<div class="modal fade" id="editTaskModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">✏️ 编辑任务</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editTaskForm">
                    <input type="hidden" id="editTaskId">
                    <div class="mb-3">
                        <label class="form-label">已完成次数</label>
                        <input type="number" class="form-control" id="editCompletedCount" min="0">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">任务备注</label>
                        <textarea class="form-control" id="editTaskNotes" rows="2"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateTask()">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let addTaskModal = null;
let editTaskModal = null;
let configData = {};
let allRoles = [];
let allTasks = [];
let selectedTaskIds = [];
let currentPage = 1;
let perPage = 100;
let sortField = 'order';
let sortOrder = 'asc';

$(document).ready(function() {
    addTaskModal = new bootstrap.Modal(document.getElementById('addTaskModal'));
    editTaskModal = new bootstrap.Modal(document.getElementById('editTaskModal'));
    loadConfig();
    setToday();
    loadTasks();
});

// 加载配置数据
async function loadConfig() {
    try {
        const data = await apiRequest('/api/config');
        configData = data.data;
        
        // 填充任务类型下拉（新增任务用）
        let taskTypeOptions = '<option value="">请选择</option>';
        configData.tasks.forEach(t => {
            taskTypeOptions += `<option value="${t.task_name}">${t.task_name}</option>`;
        });
        $('#taskType').html(taskTypeOptions);
        
        // 填充任务类型筛选下拉
        let filterTaskTypeOptions = '<option value="">全部任务类型</option>';
        configData.tasks.forEach(t => {
            filterTaskTypeOptions += `<option value="${t.task_name}">${t.task_name}</option>`;
        });
        $('#filterTaskType').html(filterTaskTypeOptions);
        
        // 加载角色列表
        const rolesData = await apiRequest('/api/roles');
        allRoles = rolesData.data;
        
        let roleOptions = '<option value="">请选择角色</option>';
        allRoles.forEach(r => {
            roleOptions += `<option value="${r.id}" data-account-id="${r.account_id}">${r.role_name} (${r.account_name})</option>`;
        });
        $('#taskRoleId').html(roleOptions);
        
    } catch (error) {
        console.error('加载配置失败:', error);
        showNotification('加载配置失败', 'error');
    }
}

// 设置今天日期
function setToday() {
    const today = new Date().toISOString().split('T')[0];
    $('#taskDate').val(today);
    $('#taskInputDate').val(today);
}

// 改变日期
function changeDate(days) {
    const currentDate = new Date($('#taskDate').val());
    currentDate.setDate(currentDate.getDate() + days);
    const dateStr = currentDate.toISOString().split('T')[0];
    $('#taskDate').val(dateStr);
    loadTasks();
}

// 加载任务
async function loadTasks() {
    try {
        const taskDate = $('#taskDate').val();
        const searchRole = $('#searchRole').val().trim();
        const searchAccount = $('#searchAccount').val().trim();
        const filterStatus = $('#filterStatus').val();
        const filterTaskType = $('#filterTaskType').val();
        const searchNotes = $('#searchNotes').val().trim();
        const searchOrderMin = $('#searchOrderMin').val().trim();
        const searchOrderMax = $('#searchOrderMax').val().trim();
        
        // 构建查询参数
        const params = new URLSearchParams({
            date: taskDate,
            page: currentPage,
            per_page: perPage,
            sort_field: sortField,
            sort_order: sortOrder
        });
        
        // 添加查询条件
        if (searchRole) params.append('role_name', searchRole);
        if (searchAccount) params.append('account_name', searchAccount);
        if (filterTaskType) params.append('task_type', filterTaskType);
        if (filterStatus) params.append('status', filterStatus);
        if (searchNotes) params.append('task_notes', searchNotes);
        if (searchOrderMin) params.append('order_min', searchOrderMin);
        if (searchOrderMax) params.append('order_max', searchOrderMax);
        
        const data = await apiRequest(`/api/tasks?${params.toString()}`);
        const tasks = data.data;
        
        // 计算统计信息
        const originalCompleted = tasks.filter(t => t.is_completed).length;
        const originalTotal = tasks.length;
        
        allTasks = tasks;
        
        // 显示统计信息（使用原始数据）
        const rate = originalTotal > 0 ? Math.round(originalCompleted / originalTotal * 100) : 0;
        $('#completionRate').text(rate + '%');
        $('#taskStats').text(`${originalCompleted}/${originalTotal}`);
        
        // 清空选择
        selectedTaskIds = [];
        $('#selectAll').prop('checked', false);
        
        if (allTasks.length === 0) {
            const emptyHTML = `
                <div class="text-center py-4">
                    <div class="empty-state">
                        <i class="bi bi-inbox"></i>
                        <p>暂无任务数据</p>
                        <button class="btn btn-success" onclick="generateTodayTasks()">生成今日任务</button>
                    </div>
                </div>
            `;
            $('#taskTableBody').html(`<tr><td colspan="11" class="text-center py-4">${emptyHTML}</td></tr>`);
            $('#taskMobileCards').html(emptyHTML);
            return;
        }
        
        // 渲染桌面端表格
        let tableHTML = '';
        allTasks.forEach(task => {
            const statusBadge = task.is_completed ? 
                '<span class="badge bg-success">已完成</span>' : 
                '<span class="badge bg-warning">未完成</span>';
            
            const completeTime = task.complete_time || '-';
            const notes = task.task_notes || '-';
            
            tableHTML += `
                <tr>
                    <td><input type="checkbox" class="task-checkbox" value="${task.id}" onchange="updateSelection()"></td>
                    <td><strong>${task.order || 0}</strong></td>
                    <td><strong>${task.role_name}</strong></td>
                    <td>${task.account_name}</td>
                    <td>${task.task_type}</td>
                    <td>${task.target_count}</td>
                    <td>${task.completed_count}</td>
                    <td>${statusBadge}</td>
                    <td><small>${completeTime}</small></td>
                    <td><small>${notes}</small></td>
                    <td>
                        <button class="btn btn-sm ${task.is_completed ? 'btn-outline-warning' : 'btn-outline-success'}" 
                                onclick="toggleTaskStatus('${task.id}')" 
                                title="${task.is_completed ? '标记未完成' : '标记完成'}">
                            <i class="bi ${task.is_completed ? 'bi-arrow-counterclockwise' : 'bi-check-circle'}"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-primary" onclick="editTask('${task.id}')" title="编辑">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteTask('${task.id}')" title="删除">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        $('#taskTableBody').html(tableHTML);
        
        // 显示分页信息
        if (data.total > perPage) {
            console.log(`显示第 ${currentPage} 页，共 ${data.pages} 页，总计 ${data.total} 条记录`);
        }
        
        // 渲染移动端卡片
        let mobileHTML = '';
        allTasks.forEach(task => {
            const statusBadge = task.is_completed ? 
                '<span class="badge bg-success">✓ 已完成</span>' : 
                '<span class="badge bg-warning">⏱ 未完成</span>';
            
            const completeTime = task.complete_time || '-';
            const notes = task.task_notes || '-';
            
            mobileHTML += `
                <div class="mobile-card-item">
                    <div class="mobile-card-header">
                        <div>
                            <input type="checkbox" class="task-checkbox form-check-input me-2" value="${task.id}" onchange="updateSelection()">
                            <span class="mobile-card-title">${task.role_name}</span>
                        </div>
                        ${statusBadge}
                    </div>
                    <div class="mobile-card-body">
                        <div class="mobile-card-field">
                            <div class="mobile-card-label">账号</div>
                            <div class="mobile-card-value">${task.account_name}</div>
                        </div>
                        <div class="mobile-card-field">
                            <div class="mobile-card-label">任务类型</div>
                            <div class="mobile-card-value">${task.task_type}</div>
                        </div>
                        <div class="mobile-card-field">
                            <div class="mobile-card-label">进度</div>
                            <div class="mobile-card-value">${task.completed_count}/${task.target_count}</div>
                        </div>
                        <div class="mobile-card-field">
                            <div class="mobile-card-label">完成时间</div>
                            <div class="mobile-card-value"><small>${completeTime}</small></div>
                        </div>
                    </div>
                    ${notes !== '-' ? `<div class="mobile-card-field" style="margin: 8px 0; font-size: 12px; color: var(--text-secondary);">备注: ${notes}</div>` : ''}
                    <div class="mobile-card-actions">
                        <button class="btn btn-sm ${task.is_completed ? 'btn-warning' : 'btn-success'}" 
                                onclick="toggleTaskStatus('${task.id}')">
                            <i class="bi ${task.is_completed ? 'bi-arrow-counterclockwise' : 'bi-check-circle'}"></i>
                            ${task.is_completed ? '取消完成' : '标记完成'}
                        </button>
                        <button class="btn btn-sm btn-primary" onclick="editTask('${task.id}')">
                            <i class="bi bi-pencil"></i> 编辑
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteTask('${task.id}')">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </div>
                </div>
            `;
        });
        $('#taskMobileCards').html(mobileHTML);
    } catch (error) {
        console.error('加载任务失败:', error);
        $('#taskTableBody').html('<tr><td colspan="10" class="text-center text-danger">加载失败</td></tr>');
    }
}

// 全选/取消全选
function toggleSelectAll() {
    const checked = $('#selectAll').prop('checked');
    $('.task-checkbox').prop('checked', checked);
    updateSelection();
}

// 更新选择状态
function updateSelection() {
    selectedTaskIds = [];
    $('.task-checkbox:checked').each(function() {
        selectedTaskIds.push($(this).val());
    });
    
    // 更新全选框状态
    const total = $('.task-checkbox').length;
    const checked = $('.task-checkbox:checked').length;
    $('#selectAll').prop('checked', total > 0 && total === checked);
}

// 显示添加任务模态框
function showAddTaskModal() {
    $('#addTaskForm')[0].reset();
    $('#taskInputDate').val($('#taskDate').val());
    addTaskModal.show();
}

// 更新账号ID
function updateAccountId() {
    const selectedOption = $('#taskRoleId option:selected');
    const accountId = selectedOption.data('account-id');
    // 账号ID会在保存时自动获取
}

// 保存任务
async function saveTask() {
    const form = document.getElementById('addTaskForm');
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const selectedOption = $('#taskRoleId option:selected');
    const accountId = selectedOption.data('account-id');
    
    const data = {
        task_date: $('#taskInputDate').val(),
        role_id: $('#taskRoleId').val(),
        account_id: accountId,
        task_type: $('#taskType').val(),
        target_count: parseInt($('#taskTargetCount').val()) || 1,
        task_notes: $('#taskNotes').val()
    };
    
    try {
        await apiRequest('/api/tasks', {
            method: 'POST',
            body: JSON.stringify(data)
        });
        
        showNotification('任务创建成功');
        addTaskModal.hide();
        loadTasks();
    } catch (error) {
        console.error('创建任务失败:', error);
        showNotification('创建任务失败: ' + error.message, 'error');
    }
}

// 生成今日任务
async function generateTodayTasks() {
    const taskDate = $('#taskDate').val();
    
    if (!confirm(`确定要为 ${taskDate} 生成任务吗？\n\n将根据角色管理中"在用"状态的角色及其任务类型自动生成任务。`)) {
        return;
    }
    
    try {
        const data = await apiRequest('/api/tasks/generate-today', {
            method: 'POST',
            body: JSON.stringify({ task_date: taskDate })
        });
        
        showNotification(data.message);
        loadTasks();
    } catch (error) {
        console.error('生成任务失败:', error);
        showNotification('生成任务失败: ' + error.message, 'error');
    }
}

// 切换任务状态
async function toggleTaskStatus(taskId) {
    try {
        await apiRequest(`/api/tasks/${taskId}/toggle`, {
            method: 'POST'
        });
        
        loadTasks();
    } catch (error) {
        console.error('切换任务状态失败:', error);
        showNotification('操作失败: ' + error.message, 'error');
    }
}

// 编辑任务
function editTask(taskId) {
    const task = allTasks.find(t => t.id === taskId);
    if (!task) {
        showNotification('任务不存在', 'error');
        return;
    }
    
    $('#editTaskId').val(task.id);
    $('#editCompletedCount').val(task.completed_count);
    $('#editTaskNotes').val(task.task_notes || '');
    
    editTaskModal.show();
}

// 更新任务
async function updateTask() {
    const taskId = $('#editTaskId').val();
    
    const data = {
        completed_count: parseInt($('#editCompletedCount').val()) || 0,
        task_notes: $('#editTaskNotes').val()
    };
    
    try {
        await apiRequest(`/api/tasks/${taskId}`, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
        
        showNotification('任务更新成功');
        editTaskModal.hide();
        loadTasks();
    } catch (error) {
        console.error('更新任务失败:', error);
        showNotification('更新失败: ' + error.message, 'error');
    }
}

// 删除任务
async function deleteTask(taskId) {
    if (!confirm('确定要删除这个任务吗？')) {
        return;
    }
    
    try {
        await apiRequest(`/api/tasks/${taskId}`, {
            method: 'DELETE'
        });
        
        showNotification('任务删除成功');
        loadTasks();
    } catch (error) {
        console.error('删除任务失败:', error);
        showNotification('删除失败: ' + error.message, 'error');
    }
}

// 批量完成
async function batchComplete() {
    if (selectedTaskIds.length === 0) {
        showNotification('请先选择要完成的任务', 'warning');
        return;
    }
    
    if (!confirm(`确定要批量完成选中的 ${selectedTaskIds.length} 个任务吗？`)) {
        return;
    }
    
    try {
        await apiRequest('/api/tasks/batch-complete', {
            method: 'POST',
            body: JSON.stringify({ task_ids: selectedTaskIds })
        });
        
        showNotification('批量完成成功');
        loadTasks();
    } catch (error) {
        console.error('批量完成失败:', error);
        showNotification('批量完成失败: ' + error.message, 'error');
    }
}

// 批量删除当天任务
async function batchDelete() {
    const taskDate = $('#taskDate').val();
    
    if (!confirm(`确定要删除 ${taskDate} 的所有任务吗？\n\n此操作不可恢复！`)) {
        return;
    }
    
    try {
        await apiRequest('/api/tasks/batch-delete', {
            method: 'POST',
            body: JSON.stringify({ task_date: taskDate })
        });
        
        showNotification('任务删除成功');
        loadTasks();
    } catch (error) {
        console.error('批量删除失败:', error);
        showNotification('批量删除失败: ' + error.message, 'error');
    }
}

// 排序表格
function sortTable(field) {
    if (sortField === field) {
        // 同一字段切换升序/降序
        sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
    } else {
        // 新字段默认升序
        sortField = field;
        sortOrder = 'asc';
    }
    currentPage = 1;
    loadTasks();
}

// 重置任务搜索
function resetTaskSearch() {
    $('#searchRole').val('');
    $('#searchAccount').val('');
    $('#filterStatus').val('');
    $('#filterTaskType').val('');
    $('#searchNotes').val('');
    $('#searchOrderMin').val('');
    $('#searchOrderMax').val('');
    currentPage = 1;
    loadTasks();
}

// 回车搜索 - 绑定所有输入框
$('#searchRole, #searchAccount, #searchNotes, #searchOrderMin, #searchOrderMax').on('keypress', function(e) {
    if (e.key === 'Enter') {
        loadTasks();
    }
});

// 下拉框改变时自动搜索
$('#filterStatus, #filterTaskType').on('change', function() {
    loadTasks();
});
</script>
{% endblock %}